﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace RemoteObject
{
    public class HeartBeatObserver
    {
        private DateTime lastBeatTime;
        private bool isHeartBeatStop;
        private Thread beatingThread;
        private static HeartBeatObserver instance;

        public static HeartBeatObserver getInstance()
        {
            if (instance == null) instance = new HeartBeatObserver();
            return instance;
        }

        private HeartBeatObserver()
        {
            isHeartBeatStop = false;
            beatingThread = new Thread(new ThreadStart(Run));
            beatingThread.Start();
            Thread.Sleep(2000);
            Thread watchThread = new Thread(new ThreadStart(Watch));
            watchThread.Start();
        }

        private void Run()
        {
            RemoteObject.RemoteObjectDownloader proxyObjectTcp = (RemoteObject.RemoteObjectDownloader)Activator.GetObject(typeof(RemoteObject.RemoteObjectDownloader),
                Common.CloudServerURL);
            do
            {
                proxyObjectTcp.HeartBeatObserver();
                lastBeatTime = DateTime.Now;
                Thread.Sleep(500);
            } while (true);
        }

        private void Watch()
        {
            do
            {
                if ((DateTime.Now - lastBeatTime).TotalSeconds > 2)
                {
                    isHeartBeatStop = true;
                }
                Console.WriteLine("Debug use, Heartbeat is STOP? Answer is : " + isHeartBeatStop);
                Thread.Sleep(1000);
            } while (true);
        }

        public bool IsHeartBeatStop()
        {
            return isHeartBeatStop;
        }

    }
}
